package com.intct.flink;

import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.RestOptions;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author gufg
 * @since 2025-06-26 09:56
 */
public class RichFunctionDemo {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.set(RestOptions.BIND_PORT, "8081");
        // 获取环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        // 源
        DataStreamSource<String> socketTextStream = env.socketTextStream("jd-node", 8888);

        // 转换
        /**
         * 1 比普通的Function多出生命周期方法:
         *      open()  : 在每次启动作业时,每个并行度都调用一次
         *      close() : 每个作业结束时,每个并行度都调用一次
         *          如果程序异常退出,不会调用close()方法
         *          只有正常退出,才会调用close方法
         */
        SingleOutputStreamOperator<Tuple2<String, Integer>> flatMapDS =
                socketTextStream.flatMap(new RichFlatMapFunction<String, Tuple2<String, Integer>>() {

            @Override
            public void open(Configuration parameters) throws Exception {
                System.out.println("调用open方法!");
            }

            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] splits = value.split(" ");
                for (String split : splits) {
                    out.collect(Tuple2.of(split, 1));
                }
            }

            @Override
            public void close() throws Exception {
                System.out.println("调用close方法!");
            }
        });

        flatMapDS.print();

        env.execute();
    }
}
